import os
import sys
import configparser

def read_config(url=None):
    config = configparser.ConfigParser()
    
    if url is not None:
        # 如果url不为空，则使用url作为配置文件的路径
        file_path = url
    else:
        # 如果url为空，则使用原始逻辑来定位配置文件
        curpath = os.path.dirname(os.path.realpath(__file__))
        file_path = os.path.join(curpath, "config.ini")
    
    # 尝试读取配置文件
    if not os.path.isfile(file_path):
        # print(f"配置文件 {file_path} 不存在")  # 可选，用于记录或调试
        return (None,) * 4
    
    config.read(file_path, encoding="utf-8")
    common_section = config["common"]
    env = common_section.get("env", "dev")
    if sys.platform.startswith('linux'):
        env = 'prod'
    port = common_section.get("port", "9000")
    db_conn_str = common_section.get("db_conn_str", "postgresql://xx.xx.xx.xx:xxxx/info")
    env_section = config[env]
    base_directory = env_section.get("base_directory", "")
        
    return (
        env,
        int(port),
        base_directory,
        db_conn_str
    )

# 检查环境变量中是否指定了配置文件路径
config_path_env_var = "MY_CONFIG_PATH"
external_config_path = os.getenv(config_path_env_var)

print(f"MY_CONFIG_PATH: {external_config_path} ")

env, port, base_directory, db_conn_str = (
    read_config(external_config_path)
)
